package com.kky.pp.view.date

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.contrarywind.view.WheelView
import com.kky.pp.R
import com.kky.pp.util.DateUtils
import com.kky.pp.view.cardstackview.internal.DisplayUtil
import java.util.Calendar


class DateSelectView : FrameLayout {
    constructor(context: Context) : this(context = context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context, attrs)
    }
    private var dateChangeListener : DateChangeListener? = null

    var monthWheelView: WheelView? = null
    var dayWheelView: WheelView? = null
    var yearWheelView: WheelView? = null

    var wheelViewDayAdapter: ArrayWheelAdapter<String>? = null
    var wheelViewYearAdapter: ArrayWheelAdapter<String>? = null
    var wheelViewMonthAdapter: ArrayWheelAdapter<String>? = null

    var yearPosition = 0
    var monthPosition = 0
    var dayPosition = 0
    private var years: MutableList<String>? = ArrayList()

    @RequiresApi(Build.VERSION_CODES.O)
    fun initView(context: Context, attrs: AttributeSet?) {
        val view: View = LayoutInflater.from(context).inflate(R.layout.view_data_select, this)
        val obtainStyledAttributes =
            context.obtainStyledAttributes(attrs, R.styleable.DateSelectView)

        monthWheelView = view.findViewById(R.id.wheel1)
        dayWheelView = view.findViewById(R.id.wheel2)
        yearWheelView = view.findViewById(R.id.wheel3)

        yearWheelView?.setLineSpacingMultiplier(4f)
        dayWheelView?.setLineSpacingMultiplier(4f)
        monthWheelView?.setLineSpacingMultiplier(4f)

        yearWheelView?.setItemsVisibleCount(5)
        dayWheelView?.setItemsVisibleCount(5)
        monthWheelView?.setItemsVisibleCount(5)


        yearWheelView?.setTypeface(context.resources.getFont(io.rong.imkit.R.font.intersemibold))
        dayWheelView?.setTypeface(context.resources.getFont(io.rong.imkit.R.font.intersemibold))
        monthWheelView?.setTypeface(context.resources.getFont(io.rong.imkit.R.font.intersemibold))
        setParams(obtainStyledAttributes)
    }
    var day=""
    fun initDate(date: String) {
        val year = date.substring(date.length - 4, date.length)
        val month = DateUtils.replace(date.substring(0, date.indexOf("-")))
        day = date.substring(date.indexOf("-")+1, date.length - 5)
        dayPosition = day.toInt() - 1
        monthPosition = month.toInt() - 1
        yearPosition = years?.indexOf(year)!!
        setDayAdapter()
        monthWheelView?.currentItem = monthPosition
        dayWheelView?.currentItem = dayPosition
        yearWheelView?.currentItem = yearPosition
    }

    fun setParams(obtainStyledAttributes: TypedArray) {
        val background =
            obtainStyledAttributes.getDrawable(R.styleable.DateSelectView_view_background)
        val textColor =
            obtainStyledAttributes.getColor(R.styleable.DateSelectView_textColorCenter, 0xffff00)
        val textSize =
            obtainStyledAttributes.getDimension(R.styleable.DateSelectView_dataTextSize, 16f)
        val isCyclic = obtainStyledAttributes.getBoolean(R.styleable.DateSelectView_isCyclic, true)
        val dividerColor =
            obtainStyledAttributes.getColor(R.styleable.DateSelectView_dividerColor, 0xffff00)
        if (background != null)
            this.background = background

        monthWheelView?.setCyclic(isCyclic)
        dayWheelView?.setCyclic(isCyclic)
        yearWheelView?.setCyclic(isCyclic)

        monthWheelView?.setTextSize(textSize)
        dayWheelView?.setTextSize(textSize)
        yearWheelView?.setTextSize(textSize)

        monthWheelView?.setTextColorCenter(textColor)
//        setOutTextColor(monthWheelView)
        dayWheelView?.setTextColorCenter(textColor)
//        setOutTextColor(dayWheelView)
        yearWheelView?.setTextColorCenter(textColor)
//        setOutTextColor(yearWheelView)

        monthWheelView?.setDividerColor(dividerColor)
        dayWheelView?.setDividerColor(dividerColor)
        yearWheelView?.setDividerColor(dividerColor)

        val d = Calendar.getInstance()
        val years = getYears(d.weekYear - 70, d.weekYear - 18)

        wheelViewYearAdapter = ArrayWheelAdapter(years)
        wheelViewMonthAdapter = ArrayWheelAdapter(DateUtils.getMonth())

        monthWheelView?.adapter = wheelViewMonthAdapter
        monthWheelView?.currentItem = Calendar.getInstance().get(Calendar.MONTH) - 1
        monthPosition = Calendar.getInstance().get(Calendar.MONTH) - 1
        monthWheelView?.setOnItemSelectedListener { index ->
            monthPosition = index
            dayPosition = 0
            setDayAdapter()
        }

        setDayAdapter()
        dayWheelView?.currentItem = Calendar.getInstance().get(Calendar.DATE) - 1
        dayPosition = Calendar.getInstance().get(Calendar.DATE) - 1
        dayWheelView?.setOnItemSelectedListener { index ->
            dayPosition = index
        }

        yearWheelView?.adapter = wheelViewYearAdapter
        yearWheelView?.currentItem = years.size - 1
        yearPosition = years.size - 1
        yearWheelView?.setOnItemSelectedListener { index ->
            yearPosition = index
            dayPosition = 0
            setDayAdapter()
            val year = wheelViewYearAdapter?.getItem(yearPosition).toString()
            dateChangeListener?.dateChange(year.toInt(),0,0)
        }
    }

    private fun setOutTextColor(monthWheelView: WheelView?) {
        val clazz = monthWheelView!!::class.java
        val paintField = clazz.getDeclaredField("paintOuterText")
        paintField.isAccessible = true
        val paintOuterText = paintField.get(monthWheelView) as Paint
        val startColor = Color.parseColor("#5C4672") // 开始颜色
        val endColor = Color.parseColor("#FFFFFF") // 结束颜色
        val linearGradient = LinearGradient(
            0f, DisplayUtil.dpToPx(context,72f).toFloat(), 0f, DisplayUtil.dpToPx(context,34f).toFloat(),
            startColor, endColor, Shader.TileMode.MIRROR
        )
        paintOuterText.setShader(linearGradient)
    }

    fun getSelectDate(style: DateSelectStyle = DateSelectStyle.MMDDYYYY): String {
        when (style) {
            DateSelectStyle.MM_DD_YYYY -> {
                var month = (monthPosition + 1).toString()
                month = if (month.length == 1) ("0$month") else month
                var day = wheelViewDayAdapter?.getItem(dayPosition).toString()
                day = if (day.length == 1) ("0$day") else day
                val year = wheelViewYearAdapter?.getItem(yearPosition).toString()
                return "$month/$day/$year"
            }

            DateSelectStyle.MMDDYYYY -> {
//                val month = (monthPosition + 1).toString()
                val month = DateUtils.getMonth()[monthPosition]
                var day = wheelViewDayAdapter?.getItem(dayPosition).toString()
                day = if (day.length == 1) ("0$day") else day
                val year = wheelViewYearAdapter?.getItem(yearPosition).toString()
                return "$month-$day-$year"
            }

            else -> {}
        }
        return ""
    }

    fun setDayAdapter() {
        wheelViewDayAdapter = ArrayWheelAdapter(
            getDay(
                wheelViewYearAdapter?.getItem(yearPosition).toString().toInt(),
                DateUtils.getMonth().indexOf(wheelViewMonthAdapter?.getItem(monthPosition) as String)
            )
        )
        dayWheelView?.adapter = wheelViewDayAdapter
        dayWheelView?.currentItem = 0
    }

    fun getYears(minYear: Int, maxYear: Int): MutableList<String> {
        years = mutableListOf()
        for (year in minYear..maxYear) {
            years!!.add(year.toString())
        }

        return years!!
    }

    fun getDay(year: Int, month: Int): MutableList<String> {
        val calendar = Calendar.getInstance()//获取Calendar对象
        calendar.set(year, month + 1, 1)//Month初始是从0开始的 也就是说Month=0相当于1月份  2就相当于3月份
        calendar.add(Calendar.DATE, -1)
        val days: MutableList<String> = ArrayList()
        for (day in 1..calendar.get(Calendar.DAY_OF_MONTH)) {
            days.add(day.toString())
        }
        return days
    }



    fun setDateChangeListener(c: Calendar, dateChangeListener: DateChangeListener) {
        this.dateChangeListener = dateChangeListener
        this.dateChangeListener?.dateChange(c.weekYear,0,0)
    }

    interface DateChangeListener{
        fun dateChange(year: Int,month: Int,day: Int)
    }
}